<script lang="ts" setup>
import { ref, watch, computed } from 'vue';
import { message } from 'ant-design-vue';
import { uploadPictureByUrlUsingPost } from "@/api/pictureController";
import type { UploadProps } from 'ant-design-vue';

interface PictureVO {
  id?: string;
  uid?: string;
  name?: string;
  status?: 'done' | 'uploading' | 'error';
  url?: string;
}

interface Props {
  /** 最大上传数量 */
  maxCount?: number;
  /** 当前图片信息（用于编辑模式） */
  picture?: PictureVO;
  /** 上传成功回调 */
  onSuccess?: (file: PictureVO) => void;
  /** 上传失败回调 */
  onError?: (error: Error) => void;
}

const props = withDefaults(defineProps<Props>(), {
  maxCount: 1,
});

const emit = defineEmits<{
  (e: 'update:modelValue', file?: PictureVO): void;
}>();

const loading = ref(false);
const fileUrl = ref<string>('');
const isValidUrl = ref(true);

// 当传入图片时初始化URL
watch(() => props.picture, (newVal) => {
  if (newVal?.url) {
    fileUrl.value = newVal.url;
  }
}, { immediate: true });

// URL校验规则
const urlPattern = /^(https?:\/\/.*\.(?:png|jpg|jpeg|gif|webp))(?:\\?.*)?$/i;

const validateImageUrl = (url: string) => {
  isValidUrl.value = urlPattern.test(url);
  return isValidUrl.value;
};

const handleUpload = async () => {
  if (!fileUrl.value) {
    message.warning('请输入图片URL');
    return;
  }

  if (!validateImageUrl(fileUrl.value)) {
    message.warning('请输入有效的图片地址（支持png/jpg/jpeg/gif/webp格式）');
    return;
  }

  loading.value = true;
  try {
    const params: API.PictureUploadRequest = {
      fileUrl: fileUrl.value,
      ...(props.picture?.id && { id: props.picture.id })
    };
    params.spaceId = props.spaceId
    const { data } = await uploadPictureByUrlUsingPost(params);

    if (data.code === 0 && data.data) {
      message.success('图片上传成功');
      emit('update:modelValue', data.data);
      props.onSuccess?.(data.data);
    } else {
      throw new Error(data.message || '图片上传失败');
    }
  } catch (error) {
    message.error(error.message || '图片上传失败');
    props.onError?.(error);
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <div class="picture-upload-container">
    <div class="url-input-group">
      <a-input
          v-model:value="fileUrl"
          placeholder="请输入图片URL"
          :status="!isValidUrl && fileUrl ? 'error' : undefined"
          @change="validateImageUrl(fileUrl)"
      >
        <template #suffix>
          <span v-if="fileUrl && !isValidUrl" class="error-icon">⚠</span>
        </template>
      </a-input>

      <a-button
          type="primary"
          :loading="loading"
          :disabled="!fileUrl || !isValidUrl"
          @click="handleUpload"
      >
        {{ loading ? '上传中...' : '提交' }}
      </a-button>
    </div>

    <div class="preview-section">
      <div v-if="fileUrl && isValidUrl" class="image-preview">
        <img
            :src="fileUrl"
            alt="图片预览"
            class="preview-image"
            @error="isValidUrl = false"
        />
        <div class="preview-hover">
          <span class="hover-text">{{ picture?.url ? '点击更换图片' : '预览图片' }}</span>
        </div>
      </div>

      <div v-else class="upload-tips">
        <div class="tips-icon">📷</div>
        <p class="tips-text">
          支持格式：PNG/JPG/JPEG/GIF/WEBP<br>
          推荐尺寸：1200x630px（2:1比例）<br>
          最大文件：2MB
        </p>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.picture-upload-container {
  width: 100%;
  max-width: 600px;
}

.url-input-group {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;

  .ant-input {
    flex: 1;
  }

  .ant-btn {
    white-space: nowrap;
  }
}

.error-icon {
  color: #ff4d4f;
  margin-right: 4px;
}

.preview-section {
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  padding: 16px;
  transition: border-color 0.3s;

  &:hover {
    border-color: #4096ff;
  }
}

.image-preview {
  position: relative;
  overflow: hidden;
  border-radius: 4px;
  background: #f5f5f5;
  aspect-ratio: 2/1;

  .preview-image {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: contain;
    transition: opacity 0.3s;
  }

  .preview-hover {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(0, 0, 0, 0.5);
    opacity: 0;
    transition: opacity 0.3s;

    .hover-text {
      color: white;
      font-size: 14px;
      text-align: center;
    }
  }

  &:hover {
    .preview-image {
      opacity: 0.8;
    }

    .preview-hover {
      opacity: 1;
    }
  }
}

.upload-tips {
  text-align: center;
  padding: 24px;

  .tips-icon {
    font-size: 32px;
    margin-bottom: 12px;
  }

  .tips-text {
    color: rgba(0, 0, 0, 0.45);
    font-size: 12px;
    line-height: 1.6;
    margin: 0;
  }
}
</style>
